package com.liuyk.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.liuyk.main.activity.R;
import com.liuyk.service.MessengerService;

/**
 * 进程通讯 -> Messenger
 * <p>
 * Created by liuyk on 2018/2/22.
 */
public class MessengerActivity extends BaseActivity implements View.OnClickListener {
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getApplicationContext(), "Service: " + msg.getData().getString("reply"), Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };
    private final Messenger mGetReplyMessenger = new Messenger(handler);//推荐使用：线程安全，使用简单

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Messenger messenger = new Messenger(service);//Service的信使Messenger
            final Message message = Message.obtain(null, 0);
            final Bundle bundle = new Bundle();
            bundle.putString("msg", "开启服务");
            message.setData(bundle);
            message.replyTo = mGetReplyMessenger;//指定Activity的Messenger，为两者数据交互
            try {
                messenger.send(message);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messenger);
        initView();
    }

    private void initView() {
        final TextView download = findViewById(R.id.start_download);
        download.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, MessengerService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        unbindService(connection);
        super.onDestroy();
    }
}
